package com.posti.ciudaddelbache.core.http;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.PlainSocketFactory;
import org.apache.http.conn.Scheme;
import org.apache.http.conn.SchemeRegistry;
import org.apache.http.conn.SocketFactory;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

public class HttpClient {
  private org.apache.http.client.HttpClient client;

  public HttpClient() {
    client = this.createHttpClient();
  }

  public String get(String uri) {
    String response = null;
    HttpEntity entity = null;
    try {
      Log log = LogFactory.getLog(this.getClass().getName() + ".get");
      log.debug(uri);

      HttpGet request = new HttpGet(uri);
      HttpResponse rsp = client.execute(request);
      entity = rsp.getEntity();

      if (entity != null) {
        response = EntityUtils.toString(rsp.getEntity());
      }
    } catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (HttpException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (entity != null) {
        try {
          // release connection gracefully
          entity.consumeContent();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }

    LogFactory.getLog(this.getClass()).warn(response);
    return response;
  }

  private final org.apache.http.client.HttpClient createHttpClient() {
    HttpParams parameters = this.setupParameters();

    DefaultHttpClient dhc = new DefaultHttpClient(
      new ThreadSafeClientConnManager(parameters, setupSupportedSchemes()),
      parameters
    );

    final HttpHost proxy = new HttpHost("proxy.globant.com", 3128, "http");
    dhc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    return dhc;
  }

  /**
   * Performs general setup. This should be called only once.
   *
   * @return
   */
  private SchemeRegistry setupSupportedSchemes() {
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));

    return supportedSchemes;
  }

  private HttpParams setupParameters() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    return params;
  }
}
